package com.yj.cmp.sdk.fusioncompute.storage.storage;

import com.yj.cmp.sdk.fusioncompute.common.utils.RequestUtils;
import com.yj.cmp.sdk.fusioncompute.storage.storage.vo.StorageDetailVo;
import com.yj.cmp.sdk.fusioncompute.storage.storage.vo.StorageListVo;
import org.springframework.stereotype.Component;
import retrofit2.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Harvey_Yang
 * @date 2021/8/28 11:16
 */
@Component
public class FcStorageApi {
    FcStorageService fcStorageService;

    public FcStorageApi(FcStorageService fcStorageService) {
        this.fcStorageService = fcStorageService;
    }

    /**
     * 存储列表
     */
    public List<StorageListVo.StorageResourcesDTO> storageList(Map<String, Object> headerMap, Map<String, Object> queryParam) throws Exception {

        Response<StorageListVo> response = fcStorageService.storageList(headerMap, queryParam).execute();
        RequestUtils.isSuccessful(response);
        List<StorageListVo.StorageResourcesDTO> list = new ArrayList<>(response.body().getStorageResources());
        if (response.body().getTotal() <= 100) {
            if (null != response.body()) {
                return response.body().getStorageResources();
            }
            return new ArrayList<>(0);
        }

        int page = (int) Math.ceil(new Double(response.body().getTotal()) / 100);
        for (int i = 2; i <= page; i++) {
            queryParam.put("offset", i);
            queryParam.put("limit", 100);
            list.addAll(fcStorageService.storageList(headerMap, queryParam).execute().body().getStorageResources());
        }
        return list;
    }

    /**
     * 存储详细
     */
    public StorageDetailVo storageDetail(Map<String, Object> headerMap, String storageId) throws Exception {
        Response<StorageDetailVo> response = fcStorageService.storageDetail(headerMap, storageId).execute();
        RequestUtils.isSuccessful(response);
        if (null != response.body()) {
            return response.body();
        }
        return new StorageDetailVo();
    }
}
